<?php

namespace App\Http\Controllers\admin;

use App\Model\AuthModel;
use App\Model\UserModel;
use Illuminate\Http\Request;
use App\Model\AdminLogsModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;


//管理员
class AuthController extends Controller
{
	//审核列表
	public function index(Request $request){
		//查询实名认证列表
		$list = AuthModel::where(function($query){
			if(request()->keywords){
				$query->where('name',request()->keywords);
			}
			if(request()->state){
				$query->where('state',request()->state);
			}
			if(request()->user){
				$id = UserModel::where('user',request()->user)->value('id');
				$query->where('uid',$id);
			}
		})
			->OrderBy('id','desc')->paginate(15);

		$pageParam['keywords'] = request()->keywords;
		$pageParam['state'] = request()->state;
		//分页
		$page = $list->appends($pageParam)->links();
		return view('admin.auth.index',compact('list','page','request'));
	}

	//实名认证(通过)
	public function auth_ok(){
		$auth_list = AuthModel::where('id',request()->id)->first();
		if(!$auth_list){
			return ['code'=>0,'msg'=>'非法入侵'];
		}
		//用户信息
		$user = UserModel::where('id',$auth_list['uid'])->first();
		DB::beginTransaction();
		try{
			AuthModel::where('id',request()->id)->update(['state'=>1,'remark'=>'']);
			UserModel::where('id',$auth_list['uid'])->update(['is_auth'=>1]);
			$msg = '用户【'.$user['user'].'】(id:'.$user['id'].') 实名认证审核通过';
			AdminLogsModel::addLog($msg);
			DB::commit();
			return ['code'=>1,'msg'=>'操作成功'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>2,'msg'=>'操作失败'];

		}
	}

	//审核失败
	public function auth_no_remark(){
		$id = request()->id;
		return view('admin.auth.check',compact('id'));
	}

	//审核失败
	public function auth_no(){
		if(!request()->remark){
			return ['code'=>0,'msg'=>'请输入驳回原因'];
		}

		DB::beginTransaction();
		try{
			$list = AuthModel::where('id',request()->id)->first();
			if(!$list){
				return ['code'=>0,'msg'=>'非法入侵'];
			}
			//用户信息
			$user = UserModel::where('id',$list['uid'])->first();
			AuthModel::where('id',request()->id)->update(['state'=>2,'remark'=>request()->remark]);
			UserModel::where('id',$list['uid'])->update(['is_auth'=>2]);
			$msg = '用户【'.$user['user'].'】(id:'.$user['id'].') 实名认证审核驳回';
			AdminLogsModel::addLog($msg);
			DB::commit();
			return ['code'=>1,'msg'=>'操作成功'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}
	}

	//编辑驳回原因
	public function edit(){
		$id = request()->id;
		$remark = request()->remark;

		DB::beginTransaction();
		try{
			AuthModel::where('id',$id)->update(['remark'=>$remark]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}

		return ['code'=>1,'msg'=>'编辑成功'];
	}
}